package com.mzj.saas.electronicVisa.tencent.contract;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.repository.core.AjaxResult;
import com.haixiaoke.saas.repository.core.BaseController;
import com.haixiaoke.saas.repository.core.HttpStatus;
import com.haixiaoke.saas.repository.core.page.TableDataInfo;
import com.haixiaoke.saas.repository.electronicVisa.pojo.ElectronicVisaContract;
import com.haixiaoke.saas.repository.electronicVisa.pojo.TencentContractTemplateModule;
import com.haixiaoke.saas.repository.electronicVisa.utils.CreateFlowUtils;
import com.haixiaoke.saas.repository.mapper.HouseMapper;
import com.haixiaoke.saas.repository.pojo.ElectronicSigningContract;
import com.haixiaoke.saas.repository.pojo.House;
import com.haixiaoke.saas.repository.pojo.OrgElectronicVisa;
import com.haixiaoke.saas.repository.service.IElectronicSigningContractService;
import com.haixiaoke.saas.repository.service.IOrgElectronicVisaService;
import com.haixiaoke.saas.repository.electronicVisa.service.TencentElectronicVisaService;
import com.haixiaoke.saas.repository.exception.BizException;
import com.mzj.saas.annotation.CheckAuth;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.repository.CommunityHouseUserRepository;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.util.LoginUserUtil;
import com.tencentcloudapi.essbasic.v20210526.EssbasicClient;
import com.tencentcloudapi.essbasic.v20210526.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

import static com.haixiaoke.saas.repository.electronicVisa.utils.CreateFlowUtils.setAgent;

/**
 * 腾讯电子签合同
 *
 * @author qixi
 * @date 2023/12/23
 */
@RestController
@RequestMapping("/electronicVisa/tencent/contract")
public class TencentContractController extends BaseController {

    @Autowired
    private TencentElectronicVisaService tencentElectronicVisaService;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private LoginUserUtil loginUserUtil;
    @Autowired
    private IOrgElectronicVisaService orgElectronicVisaService;
    @Autowired
    private IElectronicSigningContractService electronicSigningContractService;
    @Autowired
    private HouseMapper houseMapper;

    /**
     * 查询合同模板列表
     * @return
     */
    @CheckAuth
    @GetMapping("/describeTemplates")
    @ResponseBody
    public Object describeTemplates() {
        ElectronicVisaContract bean = new ElectronicVisaContract();
        Long orgId = loginUserUtil.getOrgId();
        String orgUserId = loginUserUtil.getId();
        OrgElectronicVisa orgElectronicVisa = new OrgElectronicVisa();
        orgElectronicVisa.setOrgId(orgId);
        List<OrgElectronicVisa> electronicVisas = orgElectronicVisaService.selectOrgElectronicVisaList(orgElectronicVisa);
        if (CollectionUtil.isEmpty(electronicVisas)) {
            throw new BizException(HttpStatus.ERROR, "该企业暂无电子签服务");
        }

        OrgElectronicVisa orgElectronicVisa1 = electronicVisas.get(0);
        bean.setOrgElectronicVisa(orgElectronicVisa1);
        bean.setOperatorId(orgUserId);
        DescribeTemplatesResponse describeTemplatesResponse = tencentElectronicVisaService.describeTemplates(bean);
        if (describeTemplatesResponse == null) {
            throw new BizException(HttpStatus.ERROR, "查询合同模板列表失败");
        }
        TemplateInfo[] templates = describeTemplatesResponse.getTemplates();
        return success(templates);
    }

    /**
     * 查询合同模板控件信息
     * @return
     */
    @CheckAuth
    @PostMapping("/editContractInfo/{houseId}")
    @ResponseBody
    public Object editContractInfo(@RequestBody TemplateInfo info,@PathVariable String houseId) {
        Component[] components = info.getComponents();
        components = buildFormFields(components,houseId);
        return success(components);
    }



    private Component[] buildFormFields(Component[] components, String houseId) {
        OrgElectronicVisa orgElectronicVisa = orgElectronicVisaService.selectOrgElectronicVisaByOrgId(loginUserUtil.getOrgId());

        House house = houseMapper.selectHouseById(houseId);
        if (ObjectUtil.isEmpty(house)) {
            throw new BizException(HttpStatus.ERROR, "房屋信息异常");
        }


        for (Component component : components) {
            String placeholder = component.getPlaceholder();
            switch (placeholder){
                case TencentContractTemplateModule.HOUSE_ADDRESS:
                    // House house = houseRepository.findById(houseId).get();
                    String communityName = house.getECommunityName();
                    // 地址 address= 市 + 街道 + 小区名
                    String cityName = house.getCityName();
                    String address = cityName + house.getResidenceStreetName() + communityName + house.getRoomNumber();

                    component.setComponentValue(address);
                    break;
                case TencentContractTemplateModule.ORG_NAME:
                    component.setComponentValue(orgElectronicVisa.getOrganizationName());
                    break;
                case TencentContractTemplateModule.USCC:
                    component.setComponentValue(orgElectronicVisa.getUSCC());
                    break;

                case TencentContractTemplateModule.HOUSE_TYPE:
                    String houseType = "";
                    Long room = house.getRoom();
                    Long hall = house.getHall();
                    Long toilet = house.getToilet();
                    // 数字转中文
                    String roomStr = Convert.numberToChinese(room, false);
                    String hallStr = Convert.numberToChinese(hall, false);
                    String toiletStr = Convert.numberToChinese(toilet, false);
                    if (StrUtil.isNotBlank(roomStr) ) {
                        houseType += roomStr + "室";
                    }
                    if (StrUtil.isNotBlank(hallStr)) {
                        houseType += hallStr + "厅";
                    }
                    if (StrUtil.isNotBlank(toiletStr)) {
                        houseType += toiletStr + "卫";
                    }
                    component.setComponentValue(houseType);
                    break;
                case TencentContractTemplateModule.AREA:
                    component.setComponentValue(house.getArea().toString());
                    break;
                // case TencentContractTemplateModule.LEASE_START_TIME:
                //     component.setComponentValue("2021-01-01");
                //     break;
                // case TencentContractTemplateModule.LEASE_END_TIME:
                //     component.setComponentValue("2022-02-02");
                //     break;
                // case TencentContractTemplateModule.RENT:
                //     component.setComponentValue("1000");
                //     break;
                // case TencentContractTemplateModule.CASH_PLEDGE:
                //     component.setComponentValue("1000");
                //     break;
                // case TencentContractTemplateModule.PAYMENT_DATE:
                //     component.setComponentValue("1");
                //     break;
                // case TencentContractTemplateModule.DELIVERY_PERIOD:
                //     component.setComponentValue("3");
                //     break;
                default:
                    break;
            }
        }
        return components;
    }


    /**
     * 模板流程 发起合同签署
     * @return
     */
    @PostMapping("/createFlowsByTemplates")
    @ResponseBody
    @CheckAuth
    public AjaxResult createFlowsByTemplates(@RequestBody @Valid ElectronicVisaContract bean)  {


        String houseId = bean.getHouseId();
        List<CommunityHouseUser> byCommunityHouseIdAndStatusAndType = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
        if (ObjectUtil.isEmpty(byCommunityHouseIdAndStatusAndType)) {
            throw new BizException(HttpStatus.ERROR, "该房屋暂无业主");
        }

        String userId = byCommunityHouseIdAndStatusAndType.get(0).getUserId();
        Optional<AppUser> byId = appUserRepository.findById(userId);
        if (!byId.isPresent()) {
            throw new BizException(HttpStatus.ERROR, "房屋业主信息异常");
        }

        AppUser appUser = byId.get();
        if (appUser.getCertificationStatus() == null || appUser.getCertificationStatus() != 1) {
            throw new BizException(HttpStatus.ERROR, "房屋业主信息有误");
        }
        Long contractId = bean.getContractId();
        ElectronicSigningContract electronicSigningContract = electronicSigningContractService.selectElectronicSigningContractByContractId(contractId);
        if (ObjectUtil.isEmpty(electronicSigningContract)) {
            throw new BizException(HttpStatus.ERROR, "合同信息异常");
        }

        Long contractState = electronicSigningContract.getContractState();
        if (!contractState.equals(ElectronicSigningContract.CONTRACT_STATE_NOT)) {
            throw new BizException(HttpStatus.ERROR, "合同已生成");
        }


        bean.setName(appUser.getName());
        bean.setMobile(appUser.getPhone());
        Long orgId = loginUserUtil.getOrgId();
        String orgUserId = loginUserUtil.getId();
        OrgElectronicVisa orgElectronicVisa = new OrgElectronicVisa();
        orgElectronicVisa.setOrgId(orgId);
        List<OrgElectronicVisa> electronicVisas = orgElectronicVisaService.selectOrgElectronicVisaList(orgElectronicVisa);
        if (CollectionUtil.isEmpty(electronicVisas)) {
            throw new BizException(HttpStatus.ERROR, "该企业暂无电子签服务");
        }

        OrgElectronicVisa orgElectronicVisa1 = electronicVisas.get(0);
        bean.setOrgElectronicVisa(orgElectronicVisa1);
        bean.setOperatorId(orgUserId);

        // 发起签署

        return success();
    }

    /**
     * 查询电子签合同信息列表
     */
    @GetMapping("/list")
    @CheckAuth
    public TableDataInfo list(ElectronicSigningContract electronicSigningContract) {
        startPage();
        Long id = loginUserUtil.getOrgId();
        electronicSigningContract.setOrgId(id);
        List<ElectronicSigningContract> list = electronicSigningContractService.selectElectronicSigningContractOrHouseInfoList(electronicSigningContract);
        return getDataTable(list);
    }

    /**
     * 查询企业电子签合同信息列表
     */
    @GetMapping("/contractList")
    @CheckAuth
    public TableDataInfo contractList(ElectronicSigningContract electronicSigningContract) {
        startPage();
        Long id = loginUserUtil.getOrgId();
        electronicSigningContract.setOrgId(id);
        List<ElectronicSigningContract> list = electronicSigningContractService.selectElectronicSigningContractOrHouseInfoContractList(electronicSigningContract);
        return getDataTable(list);
    }

    // /**
    //  * 导出电子签合同信息列表
    //  */
    // @PostMapping("/export")
    // public void export(HttpServletResponse response, ElectronicSigningContract electronicSigningContract) {
    //     List<ElectronicSigningContract> list = electronicSigningContractService.selectElectronicSigningContractList(electronicSigningContract);
    //     ExcelUtil<ElectronicSigningContract> util = new ExcelUtil<ElectronicSigningContract>(ElectronicSigningContract.class);
    //     util.exportExcel(response, list, "电子签合同信息数据");
    // }

    /**
     * 获取电子签合同信息详细信息
     */
    @GetMapping(value = "/{contractId}")
    public AjaxResult getInfo(@PathVariable("contractId") Long contractId) {
        return success(electronicSigningContractService.selectElectronicSigningContractByContractId(contractId));
    }

    /**
     * 新增电子签合同信息
     */
    @PostMapping
    @CheckAuth
    public AjaxResult add(@RequestBody @Valid ElectronicSigningContract electronicSigningContract) {
        Long orgId = loginUserUtil.getOrgId();
        String orgName = loginUserUtil.getOrgName();

        OrgElectronicVisa orgElectronicVisa = orgElectronicVisaService.selectOrgElectronicVisaByOrgId(orgId);
        if (orgElectronicVisa.getContractUsedNumber() >= orgElectronicVisa.getContractTotalNumber()) {
            throw new BizException(HttpStatus.ERROR, "合同数量已用完,请联系管理员");
        }


        String userPhone = electronicSigningContract.getUserPhone();
        AppUser appUser = appUserRepository.findByPhone(userPhone);

        if (ObjectUtil.isEmpty(appUser) || appUser.getCertificationStatus() != 1) {
            throw new BizException(HttpStatus.ERROR, "该手机号未注册或未实名认证");
        }


        electronicSigningContract.setOrgId(orgId);
        electronicSigningContract.setOrgName(orgName);
        electronicSigningContract.setUserId(appUser.getId());
        electronicSigningContract.setUserName(appUser.getName());

        return toAjax(electronicSigningContractService.insertElectronicSigningContract(electronicSigningContract));
    }

    /**
     * 修改电子签合同信息
     */
    @PutMapping
    public AjaxResult edit(@RequestBody ElectronicSigningContract electronicSigningContract) {
        return toAjax(electronicSigningContractService.updateElectronicSigningContract(electronicSigningContract));
    }

    /**
     * 删除电子签合同信息
     */
    @DeleteMapping("/{contractIds}")
    public AjaxResult remove(@PathVariable Long[] contractIds) {
        return toAjax(electronicSigningContractService.deleteElectronicSigningContractByContractIds(contractIds));
    }


    /**
     * 获取合同预览链接
     * @param electronicSigningContract
     * @return
     */
    @PostMapping("/previewContract")
    @CheckAuth
    public AjaxResult previewContract(@RequestBody ElectronicSigningContract electronicSigningContract) {
        Long orgId = loginUserUtil.getOrgId();
        OrgElectronicVisa orgElectronicVisa = orgElectronicVisaService.selectOrgElectronicVisaByOrgId(orgId);
        if (ObjectUtil.isNull(orgElectronicVisa)) {
            throw new BizException(HttpStatus.ERROR, "该企业暂无电子签服务");
        }

        EssbasicClient client = CreateFlowUtils.initClient();
        ChannelCreateEmbedWebUrlRequest request = new ChannelCreateEmbedWebUrlRequest();
        Agent agent = CreateFlowUtils.setAgent(orgElectronicVisa.getProxyOrganizationOpenId(),orgElectronicVisa.getProxyOperatorOpenid());
        request.setAgent(agent);
        request.setBusinessId(electronicSigningContract.getFlowId());
        request.setEmbedType("PREVIEW_FLOW_DETAIL");
        request.setHiddenComponents(false);
        try {
            ChannelCreateEmbedWebUrlResponse response = client.ChannelCreateEmbedWebUrl(request);
            if (ObjectUtil.isNull(response)) {
                throw new BizException(HttpStatus.ERROR, "获取合同预览链接失败");
            }

            String webUrl = response.getWebUrl();
            return success(webUrl);
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException(HttpStatus.ERROR, "获取合同预览链接失败");
        }
    }

}
